//
//  TTRecyclingSendViewController.m
//  TaoTuo
//
//  Created by LG on 2020/8/15.
//  Copyright © 2020 刘广. All rights reserved.
//

#import "TTRecyclingSendViewController.h"
#import "TTRecyclingSendTopView.h"
#import "TTSendBottomMailView.h"
#import "TTTTSendBottomPickGoodsView.h"
#import "TTSendBottomToShopView.h"
#import "TTRecyclingSendModel.h"
#import <UIView+TYAlertView.h>
#import "TTFillInLogisticsViewController.h"
#import "TTShopListViewController.h"
#import "TTNotNeedSendView.h"
#import "TTMyAddressViewController.h"
#import "SPPickerView.h"
#import "LLSegmentView.h"
#import "TTRecyclingSuccessViewController.h"

@interface TTRecyclingSendViewController ()<STPickerSingleDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) TTRecyclingSendTopView *topView;
@property (nonatomic, strong) TTNotNeedSendView *notNeedSendView;
@property (nonatomic, strong) TTSendBottomMailView *mailView;
@property (nonatomic, strong) TTTTSendBottomPickGoodsView *pickGoodsView;
@property (nonatomic, strong) TTSendBottomToShopView *shopView;

@property (nonatomic, strong) UIView *selectView;
@property (nonatomic, strong) NSArray *bottomViewsArray;

@property (nonatomic, strong) TTRecyclingSendModel *model;
@property (nonatomic, strong) UIButton *bottomBtn;
/// 上部视图选中的第几个视图，0：邮寄，1：上门，2：到店
@property (nonatomic, assign) NSInteger selectIndex;

@property (nonatomic, strong) NSDictionary *titlesDic;
/// 存放参数
@property (nonatomic, strong) NSArray *paramsArray;

@end

@implementation TTRecyclingSendViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if ([self getNavRightSegmentView].isHidden) {
        [self getNavRightSegmentView].hidden = NO;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorHex(#F7F7F7);
    self.title = @"去寄送";
    self.titlesDic = @{@"0" : @"申请上架", @"1" : @"填写物流信息",@"2" : @"提交",@"3" : @"提交",};
    [self getShopInfoDatas];
    
    
}

- (void)getShopInfoDatas
{
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:sendingInformation_api parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        self.model = [TTRecyclingSendModel modelWithJSON:responseObject];
        
        [self setupSubviews];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}

// 点击底部按钮
- (void)bottomBtnClick:(UIButton *)sender
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"RealName"] = [TTLoginSingle sharedSingle].loginModel.RealName;
    dic[@"Reclaim_InformationId"] = self.Reclaim_InformationId;
    if (self.selectIndex == 0) {
        dic[@"SendMethod"] = @4;
        
        [self.view makeToast:@"敬请期待！"];
        
    } else if (self.selectIndex == 1) {
        // 填写物流信息
        TTFillInLogisticsViewController *vc = [[TTFillInLogisticsViewController alloc] init];
        vc.expressListArray = self.model.ExpressList;
        vc.Reclaim_InformationId = self.Reclaim_InformationId;
        [self.navigationController pushViewController:vc animated:YES];
        
        
    } else if (self.selectIndex == 2) {
        
        if (self.pickGoodsView.model == nil) {
            [self.view makeToast:@"请选择地址"];
            return;
        }
        [dic addEntriesFromDictionary:self.paramsArray.firstObject];
        dic[@"MName"] = self.pickGoodsView.model.ReceiverName;
        dic[@"MTelPhone"] = self.pickGoodsView.model.ReceiverMobile;
        dic[@"MProvince"] = self.pickGoodsView.model.Province;
        dic[@"MCity"] = self.pickGoodsView.model.City;
        dic[@"MArea"] = self.pickGoodsView.model.Area;
        dic[@"MAddress"] = self.pickGoodsView.model.Address;
        dic[@"MRemark"] = @"";
        
        LLSystemAlertView *alertView = [LLSystemAlertView alertViewWithTitle:@"" message:@"您确定上门取货吗？" cancelTitle:@"取消" cancelBlock:^{
            
        } confirmTitle:@"确定" confirmBlock:^BOOL{
            
            [self commitResultWithDic:dic];
            
            return YES;
        }];
        [TYShowAlertView showAlertViewWithView:alertView backgoundTapDismissEnable:YES];
        
    } else if (self.selectIndex == 3) {
        [dic addEntriesFromDictionary:self.paramsArray.lastObject];
        dic[@"StoreAddress"] = self.shopView.model.storeAddress;
        dic[@"CustomerPhone"] = self.shopView.model.customerPhone;
        
        LLSystemAlertView *alertView = [LLSystemAlertView alertViewWithTitle:@"" message:@"您确定到店交易吗？" cancelTitle:@"取消" cancelBlock:^{
            
        } confirmTitle:@"确定" confirmBlock:^BOOL{
            
            [self commitResultWithDic:dic];
            
            return YES;
        }];
        [TYShowAlertView showAlertViewWithView:alertView backgoundTapDismissEnable:YES];
        
    }
    
    
    
    
}

- (void)commitResultWithDic:(NSDictionary *)dic
{
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:recyclingSend_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        /// 提交成功
        TTRecyclingSuccessViewController *sVC = [[TTRecyclingSuccessViewController alloc] init];
        sVC.Reclaim_InformationId = self.Reclaim_InformationId;
        [self.navigationController pushViewController:sVC animated:YES];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}

- (void)setupSubviews
{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - StatusBarAndNavBar_Height)];
    [self.view addSubview:_scrollView];
    
    
    @weakify(self)
    _topView = [[TTRecyclingSendTopView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 140) selectItemBlock:^(NSInteger index) {
        @strongify(self)
        NSLog(@">>>> %ld", index);
        self.selectIndex = index;
        self.selectView.hidden = YES;
        self.selectView = self.bottomViewsArray[index];
        self.selectView.hidden = NO;
        NSString *str = [NSString stringWithFormat:@"%ld", index];
        [self.bottomBtn setTitle:self.titlesDic[str] forState:UIControlStateNormal];
        
        [self.view layoutIfNeeded];
        self.scrollView.contentSize = CGSizeMake(0, self.selectView.bottom);
        
    }];
    [self.scrollView addSubview:_topView];
    
    self.mailView.model = self.model.StoreList.firstObject;
    self.pickGoodsView.time = self.model.ArrivalTime.firstObject;
    self.shopView.model = self.model.StoreList.firstObject;
    self.shopView.time = self.model.VisitingTime.firstObject;
    
    self.bottomViewsArray = @[self.notNeedSendView, self.mailView, self.pickGoodsView, self.shopView];
    
    self.selectIndex = 0;
    self.selectView = self.notNeedSendView;
    self.selectView.hidden = NO;

    
    UIView *btnBgView = [[UIView alloc] initWithFrame:CGRectMake(0, _scrollView.bottom, self.view.width, StatusBarAndNavBar_Height)];
    btnBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:btnBgView];
    _bottomBtn = [UIButton createButtonWithTitle:self.titlesDic[@"0"] titleColor:UIColor.whiteColor titleFont:[UIFont systemFontOfSize:17] backgroundColor:UIColorHex(#9343EB) cornerRadius:20 target:self action:@selector(bottomBtnClick:)];
    _bottomBtn.frame = CGRectMake(16, 10, self.view.width - 32, 40);
    [btnBgView addSubview:_bottomBtn];
    
    
    [self.view layoutIfNeeded];
    self.scrollView.contentSize = CGSizeMake(0, self.selectView.bottom);
    
    
    
    self.paramsArray = @[
        @{
            @"VisitingTime" : self.pickGoodsView.time,
            @"SendMethod" : @2,
        }.mutableCopy,
        @{
            @"ArrivalTime" : self.shopView.time,
            @"SendMethod" : @3,
        }.mutableCopy
    ];
    
}


- (void)pickerSingle:(STPickerSingle *)pickerSingle selectedTitle:(NSString *)selectedTitle
{
    UIView *view = self.bottomViewsArray[self.selectIndex];
    [view setValue:selectedTitle forKey:@"time"];
    
    NSMutableDictionary *dic = self.paramsArray[self.selectIndex - 2];
    if (self.selectIndex == 2) {
        dic[@"VisitingTime"] = selectedTitle;
    } else if (self.selectIndex == 3) {
        dic[@"ArrivalTime"] = selectedTitle;
    }
}

- (UIView *)getNavRightSegmentView
{
    UIView *segmentView;
    NSArray *views = self.navigationController.navigationBar.subviews;
    for (UIView *view in views) {
        if ([view isKindOfClass:[LLSegmentView class]]) {
            segmentView = view;
            break;
        }
    }
    return segmentView;
}

- (TTNotNeedSendView *)notNeedSendView
{
    if (!_notNeedSendView) {
        _notNeedSendView = [TTNotNeedSendView createViewFromNib];
        _notNeedSendView.hidden = YES;
        [self.scrollView addSubview:_notNeedSendView];
        [_notNeedSendView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.topView.mas_bottom);
            make.left.right.equalTo(self.view);
            make.height.mas_equalTo(500);
        }];
    }
    return _notNeedSendView;
}

- (TTSendBottomMailView *)mailView
{
    if (!_mailView) {
        _mailView = [TTSendBottomMailView createViewFromNib];
        _mailView.hidden = YES;
        [self.scrollView addSubview:_mailView];
        [_mailView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.topView.mas_bottom).mas_offset(10);
            make.left.right.equalTo(self.view);
            make.height.mas_equalTo(500);
        }];
        @weakify(self)
        _mailView.afterSelectAddressBlock = ^(TTSendBottomMailView * _Nonnull mailView) {
          @strongify(self)
            TTShopListViewController *listVC = [[TTShopListViewController alloc] initWithShopListArray:self.model.StoreList selectBlock:^(TTSendStoreListModel * _Nonnull model) {
                mailView.model = model;
            }];
            listVC.listModel = mailView.model;
            [self.navigationController pushViewController:listVC animated:YES];
        };
    }
    return _mailView;
}

- (TTTTSendBottomPickGoodsView *)pickGoodsView
{
    if (!_pickGoodsView) {
        _pickGoodsView = [TTTTSendBottomPickGoodsView createViewFromNib];
        _pickGoodsView.hidden = YES;
        [self.scrollView addSubview:_pickGoodsView];
        [_pickGoodsView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.topView.mas_bottom);
            make.left.right.equalTo(self.view);
            make.height.mas_equalTo(500);
        }];
        
        /// 选择地址
        @weakify(self)
        [_pickGoodsView.chooseAddressSubject subscribeNext:^(TTTTSendBottomPickGoodsView *  _Nullable view) {
            @strongify(self)
            TTMyAddressViewController *addressVC = [[TTMyAddressViewController alloc] initWithSelectBlock:^(TTAddressModel * _Nonnull model) {
                view.model = model;
            }];
            [self.navigationController pushViewController:addressVC animated:YES];
            // 隐藏掉右侧view
            [self getNavRightSegmentView].hidden = YES;
            
        }];
        
        /// 选择时间
        [_pickGoodsView.chooseTimeSubject subscribeNext:^(TTTTSendBottomPickGoodsView *  _Nullable view) {
            @strongify(self)
            [LLPickerViewUtilis createPickerSingleWithArrayData:self.model.ArrivalTime delegate:self];
        }];
    }
    return _pickGoodsView;
}


- (TTSendBottomToShopView *)shopView
{
    if (!_shopView) {
        _shopView = [TTSendBottomToShopView createViewFromNib];
        _shopView.hidden = YES;
        [self.scrollView addSubview:_shopView];
        [_shopView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.topView.mas_bottom);
            make.left.right.equalTo(self.view);
            make.height.mas_equalTo(500);
        }];
        @weakify(self)
        _shopView.chooseShopBlock = ^(TTSendBottomToShopView * _Nonnull view) {
            @strongify(self)
            TTShopListViewController *listVC = [[TTShopListViewController alloc] initWithShopListArray:self.model.StoreList selectBlock:^(TTSendStoreListModel * _Nonnull model) {
                view.model = model;
            }];
            listVC.listModel = self.model.StoreList.firstObject;
            [self.navigationController pushViewController:listVC animated:YES];
        };
        
        _shopView.chooseTimeBlock = ^(TTSendBottomToShopView * _Nonnull view) {
            @strongify(self)
            [LLPickerViewUtilis createPickerSingleWithArrayData:self.model.VisitingTime delegate:self];
        };
        
    }
    return _shopView;
}

@end
